package bh

import android.content.Context
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProviders
import yyee.llee.mmee.base_api_net.base_api_bean.bean.CityBean
import yyee.llee.mmee.base_api_net.base_api_bean.bean.Citys
import yyee.llee.mmee.common.databinding.ActivityAddCityBinding
import yyee.llee.mmee.viewmode.SearchViewModel
import bh.GA.Companion.SAVECURRENTITEM
import bh.GA.Companion.city
import yyee.llee.mmee.weather.adapter.HotCityAdapter
import yyee.llee.mmee.weather.adapter.SearchAdapter
import yyee.llee.mmee.weather.base.BaseWeatherActivity
import org.greenrobot.eventbus.EventBus

class DA : BaseWeatherActivity<ActivityAddCityBinding>() {
    private var TAG = "DA"
    private var saveCurrentItem = false
    private val hotCities by lazy { ArrayList<Citys>() }
    private val searchCities by lazy { ArrayList<Citys>() }
    private var searchAdapter: SearchAdapter? = null
    private var mAdapter: HotCityAdapter? = null

    private val mViewModel by lazy {
        ViewModelProviders.of(this).get(SearchViewModel::class.java)
    }

    private var isAdd: Boolean = true

    override fun initView() {

        saveCurrentItem =
            bh.FW.getParam(this, SAVECURRENTITEM, false) as Boolean

        immersionStatusBar()
        searchAdapter = SearchAdapter(this@DA, searchCities) { cityData ->
            //点击的item 先存储在跳转
            saveAndJump(cityData)
        }
        viewBinding.rvSearch.adapter = searchAdapter

        mAdapter = HotCityAdapter(hotCities) {
            //点击的item 先存储在跳转
            saveAndJump(it)
        }
        viewBinding.rvHotCity.adapter = mAdapter

//        showAds(AdConfig.IN_NEW)
        addNativeView()
    }

    private fun addNativeView() {
//        val autoConfigAdViewScope = AutoConfigAdViewScope()
//        val AdParams = AdParams()
//        AdParams.activity = this
//        AdParams.adkey = AdConfig.IN_NEW_FLOW
//        AdParams.continaer = viewBinding.flAdFlow
//        val adScope = addAd(autoConfigAdViewScope)
//        adScope?.show(AdParams)
    }


    private fun saveAndJump(citys: Citys) {
        isAdd = true
        val cityBean = CityBean("" + citys.id, citys.district, false)
        val cacheList = bh.FW.getDataList<CityBean>(this, city)
        if (!cacheList.isNullOrEmpty()) {
            if (cacheList.size >= 5) {
                Toast.makeText(this@DA, "最多能添加5个", Toast.LENGTH_SHORT).show()
                return
            } else {
                cacheList.forEach {
                    if (it.areaCode == cityBean.areaCode) {
                        isAdd = false
                        return@forEach
                    }
                }
                if (isAdd) {
                    cacheList.add(cityBean)
                    bh.FW.saveDataList(this, city, cacheList)

                    saveCurrentItem = !cacheList.isNullOrEmpty() && cacheList.size > 0
//                    val intent = Intent(this,HomeActivity::class.java)
//                    startActivity(intent)
                    finish()

                    bh.FW.setParam(
                        this,
                        SAVECURRENTITEM,
                        saveCurrentItem
                    )
                    finish()
                } else {
                    Toast.makeText(this, "相同的城市已存在", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun initListener() {
        viewBinding.tvClose.setOnClickListener {
            finish()
        }

        viewBinding.etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search()
                    return true
                }
                return false
            }
        })
    }

    private fun search() {
        val keywords = viewBinding.etSearch.text.toString()
        val searchCitysList: ArrayList<Citys> = ArrayList()
        if (!keywords.isNullOrEmpty()) {
//            val reqSearchBean = ReqSearchBean(keywords)
//            mViewModel.searchCity(reqSearchBean)
            if (hotCities.size > 0) {
                for (item in hotCities) {
                    if (item.district.contains(keywords)) {
                        searchCitysList.add(item)
                    }
                }

                mViewModel.searchCity.postValue(searchCitysList)
            } else {
                Toast.makeText(this, "请稍后再查询", Toast.LENGTH_SHORT).show()
            }


        }
    }

    override fun initData() {
        //获取热门城市
        mViewModel.getHopCity()
        mViewModel.hotCity.observe(this) {
            showHotCity(it)
        }
        mViewModel.searchCity.observe(this) {
            if (it.size > 0) {
                showSearchResult(it)
                viewBinding.rvSearch.visibility = View.VISIBLE
            } else {
                Toast.makeText(this, "抱歉未找到当前城市", Toast.LENGTH_SHORT).show()
                viewBinding.rvSearch.visibility = View.GONE
            }
        }
        mViewModel.mExceptionLiveData.observe(this, {
            Toast.makeText(this, "请检查当前网络设置", Toast.LENGTH_SHORT).show()
        })
    }

    private fun showHotCity(it: Citys) {
        var lastProvince: String = ""
        val cityArray: java.util.ArrayList<Citys> = ArrayList()
        for (item in it.result!!) {
            if (item.province != lastProvince) {
                cityArray.add(item)
            }
            lastProvince = item.province
        }


        hotCities.clear()
        hotCities.addAll(cityArray)
        mAdapter?.notifyDataSetChanged()
    }


    private fun hideKeyboard() {
        currentFocus?.let {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(it.windowToken, 0)
        }
    }

    /**
     * 展示搜索结果
     */
    private fun showSearchResult(list: List<Citys>) {
        viewBinding.rvSearch.visibility = View.VISIBLE
        searchCities.clear()
        searchCities.addAll(list)
        searchAdapter?.notifyDataSetChanged()
    }

    override fun finish() {
        hideKeyboard()
        super.finish()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            EventBus.getDefault().post("weather_back")
            finish()
        }
        return super.onKeyDown(keyCode, event)
    }

}